import { Card, Tabs, Form, Input, Select, Button, Table, Space, Modal, message, Switch, Divider, Tag, Row, Col, Statistic } from '@/utils/antd-imports';
import { PlusOutlined, EditOutlined, DeleteOutlined, ClockCircleOutlined, CheckCircleOutlined, CloseCircleOutlined, OrderedListOutlined } from '@/utils/icons';
import React, { useState } from 'react';


















const { TabPane } = Tabs;
const { Option } = Select;

const ApprovalSettings = () => {
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  
  // 审批流程数据
  const [approvalFlows, setApprovalFlows] = useState([
    { 
      id: 1, 
      name: '项目立项流程', 
      type: 'project_approval', 
      typeName: '项目立项',
      steps: [
        { id: 1, name: '部门经理审批', order: 1, role: 'department_manager' },
        { id: 2, name: '财务审批', order: 2, role: 'finance_manager' },
        { id: 3, name: '总经理审批', order: 3, role: 'general_manager' }
      ],
      status: true,
      createdAt: '2025-10-15',
      updatedAt: '2025-10-15'
    },
    { 
      id: 2, 
      name: '离职审批流程', 
      type: 'resignation_approval', 
      typeName: '离职审批',
      steps: [
        { id: 1, name: '直属领导审批', order: 1, role: 'direct_leader' },
        { id: 2, name: 'HR审批', order: 2, role: 'hr_manager' }
      ],
      status: true,
      createdAt: '2025-10-16',
      updatedAt: '2025-10-16'
    },
    { 
      id: 3, 
      name: '报销审批流程', 
      type: 'expense_approval', 
      typeName: '报销审批',
      steps: [
        { id: 1, name: '部门主管审批', order: 1, role: 'department_head' },
        { id: 2, name: '财务审核', order: 2, role: 'finance_auditor' }
      ],
      status: false,
      createdAt: '2025-10-10',
      updatedAt: '2025-10-10'
    }
  ]);

  // 审批类型选项
  const approvalTypeOptions = [
    { value: 'project_approval', label: '项目立项' },
    { value: 'resignation_approval', label: '离职审批' },
    { value: 'expense_approval', label: '报销审批' },
    { value: 'leave_approval', label: '请假审批' },
    { value: 'purchase_approval', label: '采购审批' }
  ];

  // 角色选项
  const roleOptions = [
    { value: 'department_manager', label: '部门经理' },
    { value: 'finance_manager', label: '财务经理' },
    { value: 'general_manager', label: '总经理' },
    { value: 'direct_leader', label: '直属领导' },
    { value: 'hr_manager', label: 'HR经理' },
    { value: 'department_head', label: '部门主管' },
    { value: 'finance_auditor', label: '财务审核员' }
  ];

  // 计算统计指标
  const calculateStats = () => {
    const totalFlows = approvalFlows.length;
    const activeFlows = approvalFlows.filter(flow => flow.status).length;
    const inactiveFlows = approvalFlows.filter(flow => !flow.status).length;
    const avgSteps = approvalFlows.reduce((sum, flow) => sum + flow.steps.length, 0) / approvalFlows.length;
    
    return {
      totalFlows,
      activeFlows,
      inactiveFlows,
      avgSteps: avgSteps.toFixed(1)
    };
  };

  const stats = calculateStats();

  // 显示添加流程模态框
  const showAddFlowModal = () => {
    setEditMode(false);
    setCurrentRecord(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 显示编辑流程模态框
  const showEditFlowModal = (record) => {
    setEditMode(true);
    setCurrentRecord(record);
    form.setFieldsValue({
      name: record.name,
      type: record.type,
      status: record.status,
      steps: record.steps
    });
    setModalVisible(true);
  };

  // 处理删除流程
  const handleDeleteFlow = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此审批流程吗？',
      onOk: () => {
        setApprovalFlows(approvalFlows.filter(item => item.id !== id));
        message.success('删除成功');
      }
    });
  };

  // 处理流程状态变更
  const handleFlowStatusChange = (id, checked) => {
    setApprovalFlows(approvalFlows.map(item => 
      item.id === id ? { ...item, status: checked } : item
    ));
  };

  // 处理表单提交
  const handleSubmit = () => {
    form.validateFields().then(values => {
      if (editMode) {
        setApprovalFlows(approvalFlows.map(item => 
          item.id === currentRecord.id ? { 
            ...item, 
            ...values,
            typeName: approvalTypeOptions.find(t => t.value === values.type)?.label || values.type,
            updatedAt: new Date().toISOString().split('T')[0]
          } : item
        ));
        message.success('流程更新成功');
      } else {
        const newId = approvalFlows.length > 0 ? Math.max(...approvalFlows.map(item => item.id)) + 1 : 1;
        setApprovalFlows([...approvalFlows, { 
          ...values,
          id: newId,
          typeName: approvalTypeOptions.find(t => t.value === values.type)?.label || values.type,
          createdAt: new Date().toISOString().split('T')[0],
          updatedAt: new Date().toISOString().split('T')[0]
        }]);
        message.success('流程添加成功');
      }
      setModalVisible(false);
    });
  };

  // 审批流程表格列定义
  const approvalFlowColumns = [
    {
      title: '流程名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (text, record) => (
        <div>
          <div>{text}</div>
          <div style={{ fontSize: 12, color: '#888' }}>
            类型: {record.typeName}
          </div>
        </div>
      )
    },
    {
      title: '审批步骤',
      dataIndex: 'steps',
      key: 'steps',
      render: (steps) => (
        <div>
          {steps.map(step => (
            <Tag key={step.id} color="blue" style={{ marginBottom: 4 }}>
              {step.order}. {step.name} ({step.role})
            </Tag>
          ))}
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (text, record) => (
        <Switch 
          checked={text} 
          onChange={(checked) => handleFlowStatusChange(record.id, checked)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      )
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 120
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => showEditFlowModal(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDeleteFlow(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card title="审批流程管理" bordered={false}>
        {/* 统计指标区域 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="流程总数"
                value={stats.totalFlows}
                prefix={<OrderedListOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="启用流程"
                value={stats.activeFlows}
                prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="禁用流程"
                value={stats.inactiveFlows}
                prefix={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />}
                valueStyle={{ color: '#ff4d4f' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="平均步骤数"
                value={stats.avgSteps}
                prefix={<ClockCircleOutlined style={{ color: '#faad14' }} />}
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
        </Row>

        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={showAddFlowModal}
          >
            添加审批流程
          </Button>
        </div>

        <Table 
          columns={approvalFlowColumns} 
          dataSource={approvalFlows} 
          rowKey="id"
          bordered
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条流程记录`
          }}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 添加/编辑流程模态框 */}
      <Modal
        title={editMode ? '编辑审批流程' : '添加审批流程'}
        visible={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="流程名称"
                rules={[{ required: true, message: '请输入流程名称' }]}
              >
                <Input placeholder="例如：项目立项审批流程" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="type"
                label="审批类型"
                rules={[{ required: true, message: '请选择审批类型' }]}
              >
                <Select placeholder="请选择审批类型">
                  {approvalTypeOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="status"
            label="状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked />
          </Form.Item>

          <Divider orientation="left">审批步骤设置</Divider>
          
          <Form.List name="steps">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                    <Form.Item
                      {...restField}
                      name={[name, 'order']}
                      rules={[{ required: true, message: '请输入步骤顺序' }]}
                    >
                      <Input placeholder="顺序" type="number" style={{ width: 80 }} />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'name']}
                      rules={[{ required: true, message: '请输入步骤名称' }]}
                    >
                      <Input placeholder="步骤名称" style={{ width: 200 }} />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'role']}
                      rules={[{ required: true, message: '请选择审批角色' }]}
                    >
                      <Select placeholder="审批角色" style={{ width: 200 }}>
                        {roleOptions.map(option => (
                          <Option key={option.value} value={option.value}>
                            {option.label}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <Button type="link" danger onClick={() => remove(name)}>
                      删除
                    </Button>
                  </Space>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加审批步骤
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
    </div>
  );
};

export default ApprovalSettings;